package com.yt.order.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.order.models.bo.DispatchRuleConfigSaveBO;
import com.yt.order.models.vo.DispatchRuleConfigPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.yt.order.models.service.IDispatchRuleConfigService;
import com.yt.order.models.bo.DispatchRuleConfigBO;
import com.yt.order.models.dto.DispatchRuleConfigDTO;
import com.yt.order.models.service.IDispatchRuleFilterService;
import com.yt.order.models.dto.DispatchRuleFilterDTO;
import com.yt.order.models.bo.DispatchRuleFilterSaveBO;
import com.yt.order.models.vo.DispatchRuleConfigVO;
import com.yt.order.common.config.YmlConfig;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 派单规则信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:17:40
 */

@RestController
@RequestMapping("/api/dispatchRuleConfig")
@Slf4j
@Api(value = "DispatchRuleConfigApiController",tags = "派单规则信息Api接口")
public class DispatchRuleConfigApiController {

    @DubboReference
    private IDispatchRuleConfigService dispatchRuleConfigService;

    @DubboReference
    private IDispatchRuleFilterService dispatchRuleFilterService;
    
    @Resource
    private YmlConfig ymlConfig;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<DispatchRuleConfigVO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        DispatchRuleConfigVO vo = dispatchRuleConfigService.selectByIdWithFilters(id);

        return new Result<>(vo);
    }

    @ApiOperation(value = "派单规则信息列表",notes = "派单规则信息列表")
    @PostMapping("/queryPageList")
    public Result<DispatchRuleConfigPageVO> queryPageList(DispatchRuleConfigBO bo){
        Wrapper<DispatchRuleConfigDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<DispatchRuleConfigDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        DispatchRuleConfigPageVO voPage = dispatchRuleConfigService.selectPageWithFilters(page, wrapper);

        return new Result<>(voPage);
    }

    @ApiOperation(value = "获取所有派单规则信息", notes = "获取所有派单规则信息")
    @PostMapping("/listAll")
    public Result<List<DispatchRuleConfigVO>> listAll() {
        List<DispatchRuleConfigVO> list = dispatchRuleConfigService.selectListWithFilters();
        if (list == null || list.isEmpty()) {
            log.warn("未查询到派单规则信息");
            return new Result<>(CodeEnum.FAIL_100003); // 数据不存在
        }
        log.info("成功获取派单规则信息列表，数量: {}", list.size());
        return new Result<>(list);
    }

    @ApiOperation(value = "添加派单规则信息",notes = "添加派单规则信息")
    @PostMapping(value = "/add")
    public Result insert(@RequestBody DispatchRuleConfigSaveBO saveBO) {
        boolean flag = dispatchRuleConfigService.add(saveBO);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @ApiOperation(value = "修改派单规则信息",notes = "修改派单规则信息")
    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody DispatchRuleConfigSaveBO saveBO){
        // 打印调试信息
        System.out.println("Update saveBO: " + saveBO);
        
        DispatchRuleConfigDTO dto = new DispatchRuleConfigDTO();
        
        // 手动设置各个属性
        if (saveBO.getId() != null) {
            dto.setId(saveBO.getId());
        }
        if (saveBO.getRuleName() != null) {
            dto.setRuleName(saveBO.getRuleName());
        }
        if (saveBO.getType() != null) {
            dto.setType(saveBO.getType());
        }
        if (saveBO.getStatus() != null) {
            dto.setStatus(saveBO.getStatus());
        }
        if (saveBO.getPriority() != null) {
            dto.setPriority(saveBO.getPriority());
        }
        if (saveBO.getMatchMode() != null) {
            dto.setMatchMode(saveBO.getMatchMode());
        }
        if (saveBO.getRuleDesc() != null) {
            dto.setRuleDesc(saveBO.getRuleDesc());
        }
        if (saveBO.getRevision() != null) {
            dto.setRevision(saveBO.getRevision());
        }
        
        // 设置更新时间
        dto.setUpdateTime(new Date());
        
        // 打印调试信息
        System.out.println("Update dto: " + dto);
        
        boolean flag = dispatchRuleConfigService.updateById(dto);
        
        // 如果更新成功且有过滤条件，则更新过滤条件
        if (flag && saveBO.getFilters() != null) {
            // 先删除原有的过滤条件
            Wrapper<DispatchRuleFilterDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("rule_id", saveBO.getId());
            dispatchRuleFilterService.delete(wrapper);
            
            // 再添加新的过滤条件
            for (DispatchRuleFilterSaveBO filterSaveBO : saveBO.getFilters()) {
                DispatchRuleFilterDTO filterDTO = new DispatchRuleFilterDTO();
                BeanUtils.copyProperties(filterSaveBO, filterDTO);
                filterDTO.setRuleId(saveBO.getId()); // 设置关联的规则ID
                filterDTO.setId(ymlConfig.getPkId()); // 生成新的ID
                filterDTO.setUpdateTime(new Date());
                if (filterDTO.getCreateTime() == null) {
                    filterDTO.setCreateTime(new Date());
                }
                dispatchRuleFilterService.insert(filterDTO);
            }
        }
        
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态",notes = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
            ,@ApiImplicitParam(name = "status",value = " 状态（0：禁用，1：启用）",required = true,paramType = "query", dataType = "Integer")
    })
    public Result updateStatus(Long id, Integer status){
        // 参数校验
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002);
        }

        if(status == null || (status != 0 && status != 1)){
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 检查记录是否存在
        DispatchRuleConfigDTO existing = dispatchRuleConfigService.selectById(id);
        if(existing == null){
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 正确设置要更新的字段
        DispatchRuleConfigDTO dto = new DispatchRuleConfigDTO();
        dto.setId(id);
        dto.setStatus(status);
        // 确保更新时间也被设置
        dto.setUpdateTime(new Date());
        boolean flag = dispatchRuleConfigService.updateById(dto);
        if(flag){
            log.info("派单规则状态更新成功，ID: {}, 状态: {}", id, status);
            return new Result<>();
        } else {
            log.error("派单规则状态更新失败，ID: {}, 状态: {}", id, status);
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @ApiOperation(value = "删除派单规则信息",notes = "删除派单规则信息")
    @ApiImplicitParam(name = "id",value = "派单规则信息id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        try {
            // 参数校验
            if (id == null) {
                log.warn("删除派单规则信息失败，ID为空");
                return new Result<>(CodeEnum.FAIL_100002);
            }

            // 检查记录是否存在
            DispatchRuleConfigDTO existing = dispatchRuleConfigService.selectById(id);
            if (existing == null) {
                log.warn("删除派单规则信息失败，记录不存在，ID: {}", id);
                return new Result<>(CodeEnum.FAIL_100003);
            }

            // 先删除相关的派单条件过滤信息
            Wrapper<DispatchRuleFilterDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("rule_id", id);
            dispatchRuleFilterService.delete(wrapper);

            // 再删除主记录
            boolean flag = dispatchRuleConfigService.deleteById(id);
            if (flag){
                log.info("派单规则信息删除成功，ID: {}", id);
                return new Result<>();
            } else {
                log.error("派单规则信息删除失败，ID: {}", id);
                return new Result<>(CodeEnum.FAIL_100009);
            }
        } catch (Exception e) {
            log.error("删除派单规则信息时发生异常，ID: {}", id, e);
            return new Result<>(CodeEnum.FAIL_100005);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除派单规则信息",notes = "批量删除派单规则信息")
    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids){
        if(StrUtils.isEmpty(ids)){
            return new Result(CodeEnum.FAIL_100002 );
        }
        String[] arr = ids.split(",");
        dispatchRuleConfigService.deleteBatchIds(Arrays.asList(arr));
        return new Result<>();
    }
}
